# -*- coding: utf-8 -*-
"""
@Author: thekernel
@Date: 2020/7/6 21:15
@Description: 
"""
from flask import Flask, request

import json
import pymysql
import datetime

app = Flask(__name__)


@app.route('/get', methods=["get"])
def get_word():
    page = int(request.args.get("page"))
    limit = int(request.args.get("limit"))
    now = datetime.date.today()
    three_days_ago = datetime.timedelta(days=-3)
    seven_days_ago = datetime.timedelta(days=-7)

    db = pymysql.connect("127.0.0.1", "root", "root", "english_word")
    cursor = db.cursor()

    cursor.execute(
        "SELECT `en`, `cn` FROM words "
        "WHERE TO_DAYS(`create_time`) IN (TO_DAYS('{}'), TO_DAYS('{}'), TO_DAYS('{}')) "
        "LIMIT {}, {}".format(
            now + three_days_ago, now + seven_days_ago, now, page * limit, limit))

    data = cursor.fetchall()

    cursor.close()
    db.close()
    return json.dumps([{'en': i, 'cn': j} for i, j in data], ensure_ascii=False)


@app.route('/random', methods=["get"])
def get_random_word():
    limit = int(request.args.get("limit"))
    now = datetime.date.today()
    three_days_ago = datetime.timedelta(days=-3)
    seven_days_ago = datetime.timedelta(days=-7)

    db = pymysql.connect("127.0.0.1", "root", "root", "english_word")
    cursor = db.cursor()

    cursor.execute("SELECT `en`, `cn` FROM words "
                   "WHERE TO_DAYS(`create_time`) IN (TO_DAYS('{}'), TO_DAYS('{}'), TO_DAYS('{}')) "
                   "ORDER BY rand() LIMIT {}".format(now + three_days_ago, now + seven_days_ago, now, limit))

    data = cursor.fetchall()

    cursor.close()
    db.close()
    return json.dumps([{'en': i, 'cn': j} for i, j in data], ensure_ascii=False)


if __name__ == '__main__':
    app.run(host="0.0.0.0", port=8888)
